package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;

	public class GraphicGrid extends Sprite
	{
		public const GRID_SIZE:int = 48;
		public var zoom:Number = 1;
		public var offset:Point = new Point();
		public var mdp:Point = new Point();; // mouse down point
		
		public function GraphicGrid()
		{
			drawGrid();
			
			stage.addEventListener(MouseEvent.MOUSE_DOWN, startGridDrag);
		}
		
		public function startGridDrag(event:MouseEvent):void
		{
			stage.addEventListener(MouseEvent.MOUSE_UP, endDrag);
			stage.addEventListener(Event.MOUSE_LEAVE, endDrag);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
			
			mdp.x = mouseX;
			mdp.y = mouseY;
			onMove();
		}
		
		public function endDrag(event:Event):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_UP, endDrag);
			stage.removeEventListener(Event.MOUSE_LEAVE, endDrag);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
			onMove();
		}
		
		public function onMove(event:Event=null):void
		{
			offset.x += mouseX - mdp.x;
			offset.y += mouseY - mdp.y;
			
			drawGrid();
			
			mdp.x = mouseX;
			mdp.y = mouseY;
		}
		
		public function drawGrid():void
		{
			var W:Number = stage.stageWidth;
			var H:Number = stage.stageHeight;
			var size:Number = (zoom > 0)? GRID_SIZE*zoom : 1;
			var xp:Number = offset.x % size;
			var yp:Number = offset.y % size;
			
			graphics.clear();
			graphics.lineStyle(1,0xFF);
			while(xp < W)
			{
				graphics.moveTo(xp, 0);
				graphics.lineTo(xp, H);
				xp += size;
			}
			while(yp < H)
			{
				graphics.moveTo(0, yp);
				graphics.lineTo(W, yp);
				yp += size;
			}
			graphics.endFill();
		}
	}
}